from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from forms import SearchForm
from xml.dom.minidom import parseString
from xml.dom import Node
from django.conf import settings
import urllib2
from puppy.model import Query, Response
from puppy.query.exceptions import QueryRejectionError
from models import Taste

# Service
from recommenderator.service import service

def index(request):
    search_form = SearchForm()
    return render_to_response('recommenderator/index.html', {
        'search_form': search_form,
		'MEDIA_URL': settings.MEDIA_URL,

    })

def rate(request, mbid, rating):
    print mbid
    print rating
    return HttpResponseRedirect('/audiomash/');
    
def get_search_results(request):
    if (request.method == 'GET'):
        search_form = SearchForm(request.GET)
        if search_form.is_valid():
            artist = (search_form.cleaned_data['artist']).replace(" ","+");
    
            headers = {'User-Agent': 'Mozilla/5.0'}
            api_key = '2cc4760d43e5590947adea11ce9037b1'
            url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&limit=8&artist=' + artist + '&api_key=' + api_key
            request = urllib2.Request(url, None, headers)

            response = urllib2.urlopen(request)
            sim_xml = response.read()
            sim_dom = parseString(sim_xml)

            sim_artists = sim_dom.documentElement.childNodes[1].childNodes
            resultList = list()
            for artist_node in sim_artists:
                artistReturn = []
                if not artist_node.nodeType == Node.ELEMENT_NODE:
                    continue

                print artist_node.getElementsByTagName('name')[0].firstChild.data.encode('utf-8')
                print artist_node.getElementsByTagName('image')[2].firstChild.data.encode('utf-8')
                mbid_exists = artist_node.getElementsByTagName('mbid')[0].firstChild != None
                artistReturn.append(artist_node.getElementsByTagName('name')[0].firstChild.data.encode('utf-8'))
                artistReturn.append(artist_node.getElementsByTagName('image')[2].firstChild.data.encode('utf-8'))
                artistReturn.append(get_artist_tracks(artist_node.getElementsByTagName('name')[0].firstChild.data.encode('utf-8')))
                artistReturn.append(get_artist_bio(artist_node.getElementsByTagName('name')[0].firstChild.data.encode('utf-8')))
                if mbid_exists:
                    print artist_node.getElementsByTagName('mbid')[0].firstChild.data.encode('utf-8')
                    artistReturn.append(artist_node.getElementsByTagName('mbid')[0].firstChild.data.encode('utf-8'))
                else:
                    artistReturn.append(artist_node.getElementsByTagName('name')[0].firstChild.data.encode('utf-8'))
                artistReturn.append(getwebres(artist_node.getElementsByTagName('name')[0].firstChild.data.encode('utf-8')))

		
                resultList.append(artistReturn)
    else:
        search_form = SearchForm()
        return render_to_response('recommenderator/index.html', {
        'search_form': search_form,
	'MEDIA_URL': settings.MEDIA_URL

        })

    return render_to_response('recommenderator/results.html', {
        'search_form': search_form,
		'MEDIA_URL': settings.MEDIA_URL,
		'artist_name': artist.replace("+"," "),
		'result_list': resultList
    })

def login_user(request):
    state = "Please log in below..."
    username = password = ''
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
                return HttpResponseRedirect("/audiomash/");
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

    return render_to_response('recommenderator/login.html',{'state':state, 'username': username, 
	'MEDIA_URL': settings.MEDIA_URL})

# user creation form
def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        data = request.POST.copy()
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/audiomash/")
    else:
        form = UserCreationForm()
        data, errors = {}, {}

    return render_to_response("recommenderator/register.html", {'form' : form })


# gets five of the artist's tracks..
def get_artist_tracks(artist):
            headers = {'User-Agent': 'Mozilla/5.0'}
            api_key = '2cc4760d43e5590947adea11ce9037b1'
            url = 'http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&limit=5&artist=' + artist.replace(" ","+") + '&api_key=' + api_key
            request = urllib2.Request(url, None, headers)

            response = urllib2.urlopen(request)
            sim_xml = response.read()
            sim_dom = parseString(sim_xml)
            sim_tracks = sim_dom.documentElement.childNodes[1].childNodes
	    resultList = list()
            for track_node in sim_tracks:
                if not track_node.nodeType == Node.ELEMENT_NODE:
                    continue
		track_dict = {}
		track_dict['name'] = track_node.getElementsByTagName('name')[0].firstChild.data.encode('utf-8');
		search_query = artist + "+" + track_dict['name'] + "+official"
		track_dict['video_results'] = getvideo(search_query.replace(" ","+"))
		resultList.append(track_dict);
	    return resultList
	
# gets artist's bio..
def get_artist_bio(artist):
	print artist.replace(" ","+")
	headers = {'User-Agent': 'Mozilla/5.0'}
        api_key = '2cc4760d43e5590947adea11ce9037b1'
        url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&limit=5&artist=' + artist.replace(" ","+") + '&api_key=' + api_key
        request = urllib2.Request(url, None, headers)

        response = urllib2.urlopen(request)
        sim_xml = response.read()
        sim_dom = parseString(sim_xml)
        sim_tracks = sim_dom.documentElement.childNodes[1]
	resultList = list()
	sim_tracks_bio = sim_tracks.getElementsByTagName('bio')[0];
	if type(sim_tracks_bio.getElementsByTagName('summary')[0].firstChild) is None: 
		return "This artist does not have a description."
	else: 
		return (sim_tracks_bio.getElementsByTagName('summary')[0].firstChild.data.encode('utf-8'))
	
#the shizniz
def getvideo(artist):
    	result_dict = {}
        query = Query(artist)
        result_dict['query'] = artist
        try:            
            		result_dict['video_search'] = True
            		video_results = service.search_services['video_search'].search(query).entries
            		result_dict['video_results'] = list(video_results)
        except QueryRejectionError:
            		result_dict['videoQueryRejected'] = True
	return list(video_results)
# NOT OUR OWN CODE: taken from mase-tutorial example
# Method to add a short version of the URL for descriptive purposes to show the source website
def addShortUrls(results):
    for result in results:
        shortUrl = result['link']
        if shortUrl.find('www.') >= 0:	# If there's www. remove it
            shortUrl = shortUrl[shortUrl.find('www.') + 4:]
        if shortUrl.find('http://') >= 0:	#If there's http:// remove it
            shortUrl = shortUrl[shortUrl.find('http://') + 7:]
        if shortUrl.find('/') >= 0:
            shortUrl = shortUrl[0:shortUrl.find('/')] # Get rid of the detail for example bbc.co.uk instead of bbc.co.uk/news/
        result['shortUrl'] = ' [' + shortUrl +']'
    return list(results)

def getwebres(artist):
        result_dict = {}
	query = Query(artist)
	result_dict['query'] = artist
	try:
            web_results = service.search_services['web_search'].search( query ).entries
        except QueryRejectionError:
	    print "Query failed."
	return addShortUrls(web_results)
